
#include "StdAfx.h"

#ifndef DEF_VC6

#include "HttpRequest.h"
#include <LogService.h>

#pragma comment( lib, "libcurl_imp.lib" )

HttpRequest::HttpRequest(){
	handle_ = curl_easy_init(); 
	memset( respond_, 0, sizeof( char ) * DEF_HTTP_BUFF );
	
	curl_global_init( CURL_GLOBAL_ALL );	
}

HttpRequest::~HttpRequest(){
}

size_t HttpRequest::callback_respond_from_request( void* ptr, size_t size, size_t nmemb, void* stream ){
	strncat( ( char* )stream, ( const char* )ptr, ( size * nmemb ) );

	return 0;
}

char* HttpRequest::request( char* url ){
	respond_code_ = 0;
	respond_content_type_ = 0;
	respond_size_ = 0;
	respond_speed_ = 0;
	memset( respond_, 0, sizeof( char ) * DEF_HTTP_BUFF );

	if(! handle_ )
		return respond_;

	if(! url )
		return respond_;

	curl_easy_setopt( handle_, CURLOPT_NOPROGRESS, 1L );
	curl_easy_setopt( handle_, CURLOPT_WRITEDATA, (void*)respond_ );
	curl_easy_setopt( handle_, CURLOPT_WRITEFUNCTION, HttpRequest::callback_respond_from_request );
	curl_easy_setopt( handle_, CURLOPT_URL, url );
	curl_easy_perform( handle_ );
	
	if( CURLE_OK != curl_easy_getinfo( handle_, CURLINFO_HTTP_CODE, &respond_code_ ) ){
		LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__ ) );
		return respond_;
	}

	if( CURLE_OK != curl_easy_getinfo( handle_, CURLINFO_CONTENT_TYPE, &respond_content_type_ ) ){
		LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__ ) );
		return respond_;
	}

	if( CURLE_OK != curl_easy_getinfo( handle_, CURLINFO_SIZE_DOWNLOAD, &respond_size_ ) ){
		LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__ ) );
		return respond_;
	}
	
	if( CURLE_OK != curl_easy_getinfo( handle_, CURLINFO_SPEED_DOWNLOAD, &respond_speed_ ) ){
		LOG_ERR( LOG_SERVICE( "instance" )->Log("%s - %u", __FUNCTION__, __LINE__ ) );
		return respond_;
	}

	return respond_;
}

#endif
